import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'


const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name:'/',
    redirect:'/login'
  
  },
  {
    path: '/login',
    name: 'login',
    component: ()=>import('../views/login.vue')
  },
  {
    path: '/home',
    name: 'home',
    redirect:'/home/homeTop',
    component: ()=>import('../views/home/home.vue'),
    children:[
      {
        path: 'homeTop',
        name: 'homeTop',
        component: ()=>import('../views/home/homeTop.vue')
      },
      {
        path: 'cart',
        name: 'cart',
        component: ()=>import('../views/cart/cart.vue')
      }
    ]
  }

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const token=window.sessionStorage.getItem('token');
  
  //如果先是去到登录页，就放行，否则判断是否存在token，
  //如果缺少判断，会陷在死循环里
  if(to.path==='/login'){
    next()
  }
 else {
   if (token){
    next()
  } 
  else{
    next('/')
  }}
})

export default router
